﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisNet
{
    public class DemoService
    {
        private readonly RedisClient _context;
        private readonly IDatabase _database;
        private readonly RedisService _redisService;
        //private readonly IDatabase _database;
        private readonly string _lockKey = "my_distributed_lock";
        private readonly string _lockValue = Guid.NewGuid().ToString();
        private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); // 限制同时只有一个线程可以进入
        public DemoService(/*IDatabase database*/RedisClient context, RedisService redisService)
        {
            //_database = database;
            _database = context.GetDatabase();
            _redisService = redisService;
        }


        public async Task Test()
        {
            await _database.StringSetAsync("111", "222");
        }

        public async Task PerformCriticalOperationAsync()
        {
            // 使用 SemaphoreSlim 限制并发访问
            //await _semaphore.WaitAsync();
            try
            {
                // AcquireLockAsync使用了 Redis 的原子操作，分布式环境只有一个请求会成功获取锁
                // 尝试获取锁，设置锁的过期时间为30秒
                bool acquired = await _redisService.AcquireLockAsync(_lockKey, _lockValue, TimeSpan.FromSeconds(30));

                if (acquired)
                {
                    try
                    {
                        Console.WriteLine("Lock acquired. Performing critical operation...");
                        // 执行需要加锁的操作
                        await Task.Delay(1000); // 模拟工作
                        Console.WriteLine("Critical operation completed.");
                    }
                    finally
                    {
                        // 确保释放锁
                        await _redisService.ReleaseLockAsync(_lockKey, _lockValue);
                        Console.WriteLine("Lock released.");
                    }
                }
                else
                {
                    Console.WriteLine("Failed to acquire lock. Another instance might be running.");
                }
            }
            finally
            {
                // 释放信号量
                //_semaphore.Release();
            }
        }
    }
}
